/**
 * 
 */
package uk.ac.ebi.curtain.utils.file.fasta;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

import uk.ac.ebi.curtain.utils.file.EntryMapper;
import uk.ac.ebi.curtain.utils.file.EntryMapperBean;
import uk.ac.ebi.curtain.utils.file.FileInfo;
import uk.ac.ebi.curtain.utils.file.impl.AbstractParser;
import uk.ac.ebi.curtain.utils.io.impl.BufferedRaf;

/**
 * @author mhaimel
 *
 */
public class FastaParser extends AbstractParser {
		
	@Override
	public void parseNEntry(int nCnt, BufferedRaf in, FileInfo info,EntryMapper mapper) throws IOException{
		int iCnt = 0;
		String id = null;
		String header = null;
		StringBuffer seq = new StringBuffer();
		String line = null;
		long nextPos = in.getFilePointer();
		long prevPos = nextPos;
		long currEntryPos = nextPos;
		
		while((nCnt < 0 || nCnt > iCnt) && (line = in.readLine2()) != null){
			prevPos = nextPos;
			nextPos = in.getFilePointer();
			if(StringUtils.isNotBlank(line) 
				&& line.charAt(0) == '>'){
				if(addValid(info,currEntryPos,mapper, id, header, seq)){
					++iCnt;
				}
				currEntryPos = prevPos;
				// reset values
				id = null;
				header=null;
				seq.delete(0, seq.length());
				
				// parse
				line = line.substring(1);
				int wsIdx = line.indexOf(' '); // stop at first white space 
				if(wsIdx > 0){
					id = line.substring(0,wsIdx);
					header = line.substring(wsIdx).trim();					
				} else {
					header = StringUtils.EMPTY;
					id = line;
				}
			} else {
				seq.append(line.trim());
			}
		}
		addValid(info,currEntryPos,mapper, id, header, seq);
	}

	private boolean addValid(FileInfo info,long pos, EntryMapper mapper, String id, String header,
			StringBuffer seq) {
		if(StringUtils.isNotBlank(id)
				&& null != header
				&& seq.length() > 0){
			mapper.mapEntry(new EntryMapperBean(pos,info,new String(id), new String(header), seq.toString()));
			return true;
		} else {
			return false;
		}
	}
}
